<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/extends/zTree_v3/css/zTreeStyle/zTreeStyle.css"/>
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<body>
<div style="position: relative;height: 100%;">
    <div class="ccpui-trees">
        <p class="isShowTree colorSwitch">
            <span style="float: left;color: #fff">&nbsp;&nbsp;组织机构管理</span>
            <i layadmin-event="treeFlexible" class="layui-icon layui-icon-prev"></i>
        </p>
        <div style="margin-top: 6px;">
            <ul class="ccpui-iconTree iconTrees">
                <li><a class="iconfont iconshuaxin- zTree-refresh" title="刷新"></a></li>
                <li><a class="iconfont iconwenjianjia1-copy zTree-triangle-d" title="展开"></a></li>
                <li><a class="iconfont iconfolder1 zTree-triangle-r" title="收起"></a></li>
                <input type="text" style="width: 50%" class="orgZtreeValue">
            </ul>
            <ul id="treeSelectRoles" class="ztree ccpui-listZtree"></ul>
        </div>
    </div>
    <div class="ccpui-coreContent">
        <table id="roleListTable" lay-filter="roleListTable"></table>
    </div>
</div>
<div class="resAllocationDiv" hidden style="display: none">
    <ul id="roleResAllocation" class="ztree" style="background: #fff;height: 486px;overflow: auto"></ul>
    <div style="margin: 10px;text-align: center">
        <a class="layui-btn saveAllocation">保存</a>
        <a class="layui-btn advancedSet">高级设置</a>
        <a class="layui-btn cencalData layui-btn-danger">取消</a>
    </div>
</div>
<div class="advancedSettings" hidden style="display: none">
    <ul id="allPublicResources" class="ztree" style="background: #fff;height: 485px;overflow: auto"></ul>
    <div style="margin: 10px;text-align: center">
        <a class="layui-btn saveAdvanced">保存</a>
        <a class="layui-btn cancelDatas layui-btn-danger">取消</a>
    </div>
</div>
<!-- 头部工具栏 -->
<script type="text/html" id="headerToolsBarRole">
    <div class="ccpui-enterSel">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon layui-icon-add-1"></i>
                <span>新增</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="delete">
                <i class="layui-icon">&#xe640;</i>
                <span>删除</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="query">
                <i class="layui-icon">&#xe615;</i>
                <span>查询</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="clears">
                <i class="layui-icon">&#xe9aa;</i>
                <span>重置</span>
            </a>
        </div>
        <form class="layui-form" action="" lay-filter="roleSelect" style="margin-top:10px">
            <div class="table-top-filter">
                <div class="table-filter-alone">
                    <label class="layui-form-label">角色名</label>
                    <input type="text" class="layui-input  filter-value" name="Q_roleName_SL"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">子系统名称</label>
                    <input type="text" class="layui-input  filter-value" name="Q_systemName_SL"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">是否启用</label>
                    <select class=" filter-value" name="enabled">
                        <option value=""></option>
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">角色分类</label>
                    <select class="filter-value" name="category" id="category">
                        <option value=""></option>
                    </select>
                </div>
            </div>
        </form>
    </div>
</script>
<!-- 右侧工具栏 -->
<script type="text/html" id="rightToolsBarRole">
    <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="giveRes">资源分配</a>
    <a class="layui-btn layui-btn-xs" lay-event="userRoleAdd">人员分配</a>
    {{# if(d.enabled == 0){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" value="0" lay-event="runEnable">启用</a>
    {{# }else{ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" value="1" lay-event="runEnable">禁用</a>
    {{# } }}
</script>
<script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script src="${ctx}/extends/zTree_v3/js/jquery.ztree.all.min.js" type="text/javascript"></script>
<script src="${ctx}/extends/zTree_v3/js/jquery.ztree.exhide.min.js" type="text/javascript"></script>
<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index', 'setter', 'commons', 'form', 'jquery', 'layer', 'common', 'table', 'totalFilter'], function () {
        var table = layui.table, layer = layui.layer, setter = layui.setter, commons = layui.commons,
            common = layui.common, totalFilter = layui.totalFilter, form = layui.form, $ = layui.jquery;
        var selectRoleId = "";//选中的左侧角色树的节点ID
        var allPublicResId = [];//公共资源id选择   保存用
        var allPublicResIds = [];//公共资源id选择  高级配置   保存用
        // $('body > div.resAllocationDiv ').remove();
        // $('body').append($('div.resAllocationDiv'));
        // $('body > div.advancedSettings ').remove();
        // $('body').append($('div.advancedSettings'));

        roleZtree();
        function roleZtree() {
            $.ajax({
                url: serverPath.systemPath + setter.sysLinkPath + "sysOrg/list",
                type: "get",
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) {
                    var zNodes = data.data;
                    var setting = {
                        view:{
                            nameIsHTML: true
                        },
                        edit: {
                            enable: false,
                            editNameSelectAll: false
                        },
                        data: {
                            simpleData: {
                                enable: true,
                                idKey:"orgId",
                                pIdKey:"orgSupId"
                            }
                        },
                        callback: {
                            onClick: onClickRoles,
                        }
                    };
                    $.fn.zTree.init($('#treeSelectRoles'), setting, zNodes);
                    component.fuzzySearch('treeSelectRoles', '.orgZtreeValue', null, true); //初始化模糊搜索方法
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                },
            });
        }

        function onClickRoles(event, treeId, treeNode, clickFlag) {
            selectRoleId = treeNode.orgId;
            common.tableConditionRender("roleListTable", "roleSelect", {where: {"orgId": treeNode.orgId}}, true);
            reflashOrgSelects();
        }

        //展开
        $(".iconTrees .zTree-triangle-d").click(function () {
            $.fn.zTree.getZTreeObj("treeSelectRoles").expandAll(true);
        });
        //收起
        $(".iconTrees .zTree-triangle-r").click(function () {
            $.fn.zTree.getZTreeObj("treeSelectRoles").expandAll(false);
        });
        //刷新
        $(".iconTrees .zTree-refresh").click(function () {
            roleZtree();
        });

        var tableHeight = commons.tabHeight();
        table.render({
            elem: '#roleListTable',
            cellMinWidth: 80,
            title: '角色信息列表',
            height: tableHeight,
            defaultToolbar: ['filter', 'print'],
            url: serverPath.systemPath + setter.sysLinkPath + 'sysRole/list',
            page: true,
            method: 'get',
            toolbar: '#headerToolsBarRole',
            cols: [
                [
                    {type: 'checkbox'},
                    {field: 'roleId', title: 'ID', sort: true, hide: true},
                    {field: 'roleName', align: "center", title: '角色名', sort: true},
                    {field: 'systemName', align: "center", title: '子系统名称'},
                    {field: 'memo', title: '备注', align: "center"},
                    {field: 'category', align: "center", title: '角色分类', sort: true},
                    {
                        field: 'allowDel', width: 80, align: 'center', title: '删除',
                        templet: function (d) {
                            if (d.allowDel == 0) {
                                return '不允许';
                            }
                            return '允许';
                        },
                    },
                    {
                        field: 'allowEdit', width: 80, align: 'center', title: '编辑',
                        templet: function (d) {
                            if (d.allowEdit == 0) {
                                return '不允许';
                            }
                            return '允许';
                        }
                    },
                    {
                        field: 'enabled', width: 80, align: 'center', title: '状态',
                        templet: function (d) {
                            if (d.enabled == 0) {
                                return '不启用';
                            }
                            return '启用';
                        }
                    },
                    {align: 'center', title: '管理', toolbar: '#rightToolsBarRole'}
                ]
            ],
            done: function () {
                common.tableSelectCon('.ccpui-enterSel .layui-form input', 'a[lay-event=query]', '.ccpui-enterSel')
            }
        });
        totalFilter.init('roleListTable');
        //监听头工具栏事件
        table.on('toolbar(roleListTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    layer.open({
                        type: 2,
                        area: ['80%', '80%'],
                        title: ['新增角色信息'],
                        content: serverPath.systemPath + setter.sysLinkPath + 'sysRole/view/addEdit?selectRoleId=' + selectRoleId
                    });
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请先选择一行数据！');
                    } else {
                        layer.confirm('确定删除当前数据吗？', function () {
                            var seleIds = [];
                            for (var i = 0; i < data.length; i++) {
                                seleIds.push(data[i].roleId);
                            }
                            $.ajax({
                                url: serverPath.systemPath + setter.sysLinkPath + "sysRole/del",
                                type: "post",
                                dataType: 'json',
                                data: {roleId: seleIds.join(",")},
                                success: function (data) {
                                    if (commons._filterRecord(data)) {
                                        layer.alert(data.msg);
                                        table.reload('roleListTable', {
                                            page: {curr: 1, limit: 10},
                                        });
                                        reflashOrgSelects();
                                        totalFilter.init('roleListTable');
                                    } else {
                                        layer.alert(data.msg);
                                    }
                                }
                            })
                        })
                    }
                    break;
                case 'query':
                    common.tableConditionRender("roleListTable", "roleSelect", {where: {"orgId": selectRoleId}}, false);
                    reflashOrgSelects();
                    break;
                case 'clears':
                    common.tableConditionRender("roleListTable", "roleSelect", {where: {"orgId": selectRoleId}}, true);
                    reflashOrgSelects();
                    break;
            }
        });

        //监听行工具事件
        table.on('tool(roleListTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'detail':
                    layer.open({
                        type: 2,
                        area: ['700px', '510px'],
                        title: ['查看角色信息'],
                        content: serverPath.systemPath + setter.sysLinkPath + 'sysRole/view/view?roleId=' + data.roleId,
                    });
                    break;
                case 'del':
                    layer.confirm('确定删除当前数据吗？', function (index) {
                        layer.close(index);
                        $.ajax({
                            url: serverPath.systemPath + setter.sysLinkPath + "sysRole/del",
                            type: "post",
                            dataType: 'json',
                            data: {roleId: obj.data.roleId},
                            success: function (data) {
                                if (commons._filterRecord(data)) {
                                    layer.alert(data.msg);
                                    table.reload('roleListTable', {
                                        page: {curr: 1, limit: 10}
                                    });
                                    totalFilter.init('roleListTable');
                                    reflashOrgSelects();
                                } else {
                                    layer.alert(data.msg);
                                }
                            }
                        })
                    });
                    break;
                case 'edit':
                    layer.open({
                        type: 2,
                        area: ['900px', '568px'],
                        title: ['修改角色信息'],
                        content: serverPath.systemPath + setter.sysLinkPath + 'sysRole/view/addEdit?roleId=' + data.roleId + '&selectRoleId=' + selectRoleId
                    });
                    break;
                case 'giveRes':
                    var indexadv = layer.open({
                        type: 1,
                        area: ['400px', '600px'],
                        title: ['资源分配'],
                        content: $(".resAllocationDiv"),
                        success: function () {
                            $.ajax({
                                url: serverPath.systemPath + setter.sysLinkPath + "sysRes/queryTreeByRoleId",
                                type: "get",
                                contentType: 'application/json',
                                dataType: 'json',
                                data: {
                                    roleId: data.roleId,
                                    type: "0"

                                },
                                success: function (data) {
                                    var zNodes = data.data;
                                    var setting = {
                                        check: {
                                            enable: true
                                        },
                                        data: {
                                            simpleData: {
                                                enable: true,
                                                idKey: "resId",
                                                pIdKey: "parentId"
                                            }
                                        }
                                    };
                                    $.fn.zTree.init($('#roleResAllocation'), setting, zNodes);
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                                },
                            });
                            $.ajax({
                                url: serverPath.systemPath + setter.sysLinkPath + "sysRes/queryTreeByRoleId",
                                type: "get",
                                contentType: 'application/json',
                                dataType: 'json',
                                data: {
                                    roleId: data.roleId,
                                    type: "1",
                                },
                                success: function (data) {
                                    var zNodes = data.data;
                                    var setting = {
                                        check: {
                                            enable: true
                                        },
                                        data: {
                                            simpleData: {
                                                enable: true,
                                                idKey: "resId",
                                                pIdKey: "parentId"
                                            }
                                        },
                                        callback: {
                                            onAsyncSuccess: zTreeOnAsyncSuccess
                                        }
                                    };
                                    $.fn.zTree.init($('#allPublicResources'), setting, zNodes);
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                                },
                            });

                            function zTreeOnAsyncSuccess() {
                                allPublicResId = [];
                                var treeObj = $.fn.zTree.getZTreeObj("allPublicResources");
                                var nodes = treeObj.getCheckedNodes(true);
                                $.each(nodes, function (i, item) {
                                    if (item.resId !== "0") {
                                        allPublicResId.push(item.resId);
                                    }
                                });
                            }

                            //高级设置
                            $('.resAllocationDiv .advancedSet').unbind("click");
                            $(".resAllocationDiv .advancedSet").bind('click', function () {
                                var indexAdvanced = layer.open({
                                    type: 1,
                                    area: ['380px', '603px'],
                                    title: ['公用资源分配'],
                                    content: $(".advancedSettings"),
                                });
                                $(".advancedSettings .saveAdvanced").click(function () {
                                    zTreeOnAsyncSuccess();
                                    layer.close(indexAdvanced);
                                });
                                $(".advancedSettings .cancelDatas").click(function () {
                                    zTreeOnAsyncSuccess();
                                    layer.close(indexAdvanced);
                                });
                                return false
                            });


                            $(".resAllocationDiv .cencalData").click(function () {
                                layer.close(indexadv);
                                return false
                            });
                            $('.resAllocationDiv .saveAllocation').unbind("click");
                            $(".resAllocationDiv .saveAllocation").bind('click', function () {
                                $(".saveAllocation").attr("disabled","disabled").css("pointer-events","none");
                                if (allPublicResId.length < 1) {
                                    zTreeOnAsyncSuccess()
                                }
                                allPublicResIds = [];
                                var treeObj = $.fn.zTree.getZTreeObj("roleResAllocation");
                                var nodes = treeObj.getCheckedNodes(true);
                                $.each(nodes, function (i, item) {
                                    if (item.resId !== "0") {
                                        allPublicResIds.push(item.resId);
                                    }
                                });
                                var resIds = allPublicResId.concat(allPublicResIds);
                                $.ajax({
                                    url: serverPath.systemPath + setter.sysLinkPath + "roleResources/add",
                                    type: "post",
                                    dataType: 'json',
                                    data: {
                                        roleId: data.roleId,
                                        resId: resIds.join(","),
                                    },
                                    success: function (data) {
                                        if (commons._filterRecord(data)) {
                                            layer.alert(data.msg, function () {
                                                layer.closeAll();
                                            });
                                        } else {
                                            layer.alert(data.msg);
                                        }
                                        $(".saveAllocation").attr("disabled",false).css("pointer-events","auto");
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        $(".saveAllocation").attr("disabled",false).css("pointer-events","auto");
                                        layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
                                    },
                                });
                                return false
                            });
                        }
                    });
                    break;
                case 'userRoleAdd':
                    layer.open({
                        type: 2,
                        area: ['1050px', '585px'],
                        title: ['人员分配'],
                        content: serverPath.systemPath + setter.sysLinkPath + 'sysRole/view/distributionOfStaff?roleId=' + data.roleId + '&orgId=' + selectRoleId
                    });
                    break;
                case 'runEnable':
                    var currentEle = $(this);
                    var tit = '';
                    if (currentEle.attr("value") == 0) {
                        tit = '确定将此角色置为启用吗？'
                    } else {
                        tit = '确定将此角色置为禁用吗？'
                    }
                    layer.confirm(tit, function () {
                        $.ajax({
                            url: serverPath.systemPath + setter.sysLinkPath + "sysRole/runEnable",
                            type: "post",
                            dataType: 'json',
                            data: {
                                roleId: data.roleId,
                            },
                            success: function (data) {
                                if (commons._filterRecord(data)) {
                                    layer.msg(data.msg);
                                    currentEle.attr("value") == 0 ? currentEle.html("启用") : currentEle.html("禁用");
                                    currentEle.attr("value") == 0 ? currentEle.attr("value", '1') : currentEle.attr("value", '0');
                                    table.reload('roleListTable');
                                } else {
                                    layer.msg(data.msg);
                                }
                            },
                        });
                    });
                    break;
            }
        });
        //初始化角色分类搜索
        reflashOrgSelects();
        layui.Initializations = function () {
            reflashOrgSelects();
        };

        function reflashOrgSelects() {
            $.ajax({
                url: serverPath.systemPath + setter.sysLinkPath + "sysRole/queryDistinctCategory",
                type: "get",
                contentType: 'application/json',
                dataType: 'json',
                async: false,
                data: {orgId: selectRoleId ? selectRoleId : ""},
                success: function (data) {
                    if (commons._filterRecord(data)) {
                        var datas = data.data;
                        var optionData = "";
                        for (var i = 0; i < datas.length; i++) {
                            optionData += "<option value='" + datas[i] + "'>" + datas[i] + "</option>"
                        }
                        $("#category").append(optionData);
                        form.render("select");
                    } else {
                        window.parent.layer.alert(data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("获取数据失败！" + XMLHttpRequest.status);
                },
            });
        }
        common.tableSort('roleListTable', {show: reflashOrgSelects});
    });
</script>
</body>
</html>
<link rel="stylesheet" href="${ctx}/css/font/iconfontie.css" media="all"/>
<link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>